package org.fuys.coder.application.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.fuys.coder.common.entity.Result;
import org.fuys.coder.common.constants.RedisConstants;
import org.fuys.coder.common.constants.ResultMessageConstants;
import org.fuys.coder.common.holder.UserHolder;
import org.fuys.coder.common.util.JWTUtil;
import org.fuys.coder.infrastructure.util.RedisUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.common.interceptor
 * @className: LoginInterceptor
 * @author: WangJing
 * @description: 登录检测拦截器
 * @date: 2024/6/21 16:35
 * @version: 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {


    public RedisUtil redisUtil;
    public ObjectMapper objectMapper=new ObjectMapper();

    public LoginInterceptor(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是预检请求 直接放行
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        //如果JWT检查失败 或者是损坏 直接返回错误信息
        if(!JWTUtil.checkToken(request)){
            return response(Result.error(ResultMessageConstants.USER_INFO_ERROR),response);
        }

        //获取用户信息 检查是否是封号状态 这里使用redis的指定工作key来进行
        //todo 未来可能引入布隆过滤器
        Integer userId=null;
        try {
            userId = JWTUtil.getUserId(request);
        } catch (Exception e) {
            return response(Result.error(ResultMessageConstants.NO_USER_TOKEN),response);
        }
        final String redisKey = RedisConstants.REDIS_FIELD_USER + RedisConstants.REDIS_USE_STOP + userId;
        final Object o = redisUtil.commonGet(redisKey);
        if(!ObjectUtils.isEmpty(o)){
           // 此用户是封禁用户
            return response(Result.error("账号封禁中"),response);
        }
        if(ObjectUtils.isEmpty(userId)){
            return response(Result.error(ResultMessageConstants.NO_USER_TOKEN),response);
        }
        UserHolder.set(userId);
        return true;
    }

    private boolean response(Result result,HttpServletResponse response) throws IOException{
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Cache-Control","no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(objectMapper.writeValueAsString(result));
        response.getWriter().flush();
        return false;
    }
}
